package updown.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import updown.constant.GeneralConstant;
import updown.constant.LogConstant;
import updown.controller.other.BaseController;
import updown.data.SseCacheData;
import updown.domain.*;
import updown.service.updown.RollbackService;
import updown.util.RandomUtil;

/**
 * <p>Title: updown.controller </p>
 * <p>Description:updown:  </p>
 *
 * @Author:jiangkaixin
 * @Date:2022/1/5
 * @Version: 1.0
 */
@Slf4j
@Controller
@RequestMapping("/rollback")
public class RollbackController extends BaseController {
    @Autowired
    private RollbackService rollbackService;

    @Autowired
    private SseCacheData sseCacheData;

    /**
     * 选择本地的一个服务
     * @param file
     * @return
     */
    @PostMapping("/rollback")
    @ResponseBody
    public String rollback(@RequestBody ServiceMapVo vo) {
        vo.scheduleTask();
        log.info("rollback(),vo:{}",vo);
        if (StringUtils.isEmpty(vo.getLocalFilePath())){
            return "本地路径不能为空";
        }
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        String taskId = RandomUtil.getRandomStr();
        sseCacheData.put(taskId, sseEmitter);

        // 1. 创建 serviceInfo 信息
        ServiceInfo serviceInfo = ServiceInfo.builder().serviceName(vo.getServiceName()).build();
        // 2 创建 task
        Jar jar = Jar.builder()
                .version(vo.getJarVersionInfo())
                .originalFileName(vo.getOriginalFileName())
                .localFileLocation(vo.getLocalFilePath()).build();

        DownUpSchedule downUpSchedule = DownUpSchedule.builder()
                .scheduleTime(vo.getScheduleTime())
                .jarVersionInfo(vo.getJarVersionInfo())
                .originalFileName(vo.getOriginalFileName())
                .localFilePath(vo.getLocalFilePath()).build();
        // 3 taskWrapper
        TaskWrapper taskWrapper = TaskWrapper.builder().jar(jar)
                .downUpSchedule(downUpSchedule)
                .taskId(taskId)
                .taskType(GeneralConstant.TASK_WRAPPER_DOWN_UP_ROLLBACK)
                .serviceInfo(serviceInfo)
                .build();
        rollbackService.rollBackInPool(taskWrapper);

        log.info("提交任务，返回定时任务信息:{}", taskWrapper);
        addLog("服务回滚：" + vo.getServiceName(), LogConstant.MODULE_ROLLBACK);
        return taskId;
    }
}
